package dao

import (
	"main/model"
	"main/tool"
)

type ShopDao struct {
	*tool.OrmEngine
}

const DefaultRange = 5

func NewShopDao() *ShopDao {
	return &ShopDao{
		tool.DbEngine,
	}
}

func (sd *ShopDao) QueryServiceByShopId(shopId int64) []model.Service {
	var services []model.Service
	err := sd.Table("service").
		Join(
			"inner",
			"shop_service",
			"shop_service.service_id = service.id",
			).
		Where("shop_service.shop_id = ?", shopId).
		Find(&services)
	if err != nil {
		return nil
	}
	return services
}

func (sd *ShopDao) QueryShops(lgt, lat float64, keyword string) ([]model.Shop, error) {
	var shops []model.Shop

	var params []interface{}
	params = append(
		params,
		lgt-DefaultRange,
		lgt+DefaultRange,
		lat-DefaultRange,
		lat+DefaultRange,
	)
	query := " longitude between ? and ? and latitude between ? and ? "

	if keyword != "" {
		query = query + " and name like ? "
		params = append(params, "%" + keyword + "%")
	}

	err := sd.Engine.Where(query, params...).Find(&shops)
	if err != nil {
		return nil, err
	}
	return shops, nil
}
